﻿
namespace SvCore.Tcp;

public partial class SvTcp : ISv
{
    // port
    public int Port = 6666;
    public Func<IAppSession, ValueTask> OnConnected = null;
    public Func<IAppSession, CloseEventArgs, ValueTask> OnClosed = null;

    public string Name()
    {
        return nameof(SvTcp);
    }

    public void Init()
    {
        loger.Debug($"{Name()} Init");

        Core.DictEvt[EvtType.EvTypeTcp] = Exec;
    }

    public void Run()
    {
        loger.Debug($"{Name()} Run");

        var host = SuperSocketHostBuilder.Create<MyPackage, MyPackageFilter>()
            .UseSession<MySession>()
            .UseSessionHandler(OnConnected, OnClosed)
            .UsePackageHandler(async (s, p) =>
            {
                // handle package
                p.Session = (MySession)s;
                var evt = new Evt() { Type = EvtType.EvTypeTcp, Data = p };
                Core.QueueEvt.Enqueue(evt);

                await Task.Delay(0);
            })
            .ConfigureSuperSocket(options =>
            {
                options.Name = "CustomProtocol Server";
                options.Listeners = new List<ListenOptions>
                    {
                        new ListenOptions
                        {
                            Ip = "Any",
                            Port = Port
                        }
                    };
            })
            .ConfigureLogging((hostCtx, loggingBuilder) =>
            {
                //loggingBuilder.AddConsole();
                loggingBuilder.SetMinimumLevel(LogLevel.Warning);
            })
            .Build();


        host.Run();
        //await host.RunAsync();
    }

    public void Destroy()
    {
        loger.Debug($"{Name()} Destroy");
    }

    public void Exec(Evt evt)
    {
        var pack = (MyPackage)evt.Data;
        Exec(pack);
    }
}
